package org.twndmv.ejb;

import java.io.InputStream;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.annotation.security.RolesAllowed;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.xml.bind.JAXBException;
import javax.xml.stream.XMLStreamException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.twndmv.bl.DmvTestUtil;
import org.twndmv.blimpl.DmvTestUtilImpl;
import org.twndmv.dao.PersonDAO;
import org.twndmv.dao.VehicleRegistrationDAO;
import org.twndmv.jpa.PersonDAOImpl;
import org.twndmv.jpa.VehicleRegistrationDAOImpl;

@Stateless 
@RolesAllowed({ "dmv-admin" })
public class DmvTestUtilEJB implements DmvTestUtilRemote {
	private static Log log = LogFactory.getLog(DmvTestUtilEJB.class);

	@PersistenceContext(unitName = "dmvEntity")
	private EntityManager em;

	@Resource
    private SessionContext ctx;
	
	private DmvTestUtil testUtil;

	@PostConstruct
	public void init() {
		testUtil = new DmvTestUtilImpl();
		testUtil.setEntityManager(em);
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public void resetAll() { 
		log.debug("\n\n\ncaller=" + ctx.getCallerPrincipal().getName() + "\n\n\n");
		testUtil.resetAll();
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public void populate() {
		PersonDAO personDB = new PersonDAOImpl(em);
		VehicleRegistrationDAO vehicleDB = new VehicleRegistrationDAOImpl(em);
		String fileName = "dmv-data.xml";
		InputStream is = Thread.currentThread().getContextClassLoader()
				.getResourceAsStream(fileName);
		try {
			testUtil.populate(personDB, vehicleDB, is);
		} catch (JAXBException e) {
			log.error("Error marshalling data, " + e);
		} catch (XMLStreamException e) {
			log.error("Error reading stream for data, " + e);
		} catch (Exception e) {
			log.error("Error during populate, " + e);
		}
	}

}
